package admin

import (
	"context"
	"grpc.getaway.adminspro.padmins.com/internal/rpc/utils/database"
	"grpc.getaway.adminspro.padmins.com/pkg/config/businessError"
	"grpc.getaway.adminspro.padmins.com/pkg/libs/utils"
	pbAdmin "grpc.getaway.adminspro.padmins.com/pkg/proto/admin"
)

func (rpc *admin) AdminOperationLogAdd(ctx context.Context, pb *pbAdmin.AdminOperationLogAddReq) (*pbAdmin.AdminOperationLogAddResp, error) {

	if pb.AdminOperationLog == nil {
		return nil, businessError.ErrorInfoToRpcError(businessError.ParamsInvalid)
	}

	if pb.AdminOperationLog.AdminId == 0 {
		return nil, businessError.ErrorInfoToRpcError(businessError.ErrorfByErrorInfo(businessError.ParamsInvalidF, "AdminId参数不能为空"))
	}

	if pb.AdminOperationLog.Username == "" {
		return nil, businessError.ErrorInfoToRpcError(businessError.ErrorfByErrorInfo(businessError.ParamsInvalidF, "Username参数不能为空"))
	}

	Db := database.Db.GetDefaultDb(ctx)
	rowCount, dbErr := Db.Insert("admin_log", map[string]interface{}{
		"admin_id":    pb.AdminOperationLog.AdminId,
		"username":    pb.AdminOperationLog.Username,
		"url":         utils.MbSubStr(pb.AdminOperationLog.Url, 0, 255),
		"title":       pb.AdminOperationLog.Title,
		"content":     pb.AdminOperationLog.Content,
		"ip":          pb.AdminOperationLog.Ip,
		"useragent":   utils.MbSubStr(pb.AdminOperationLog.Useragent, 0, 1000),
		"create_time": utils.Date("Y-m-d H:i:s"),
	})

	if dbErr != nil {
		return nil, businessError.ErrorInfoToRpcError(businessError.DbError(dbErr))
	}

	if rowCount == 0 {
		return nil, businessError.ErrorInfoToRpcError(businessError.OperateError)
	}

	LastInsertId, dbErr := Db.LastInsertId()

	if dbErr != nil {
		return nil, businessError.ErrorInfoToRpcError(businessError.DbError(dbErr))
	}

	return &pbAdmin.AdminOperationLogAddResp{
		Id: LastInsertId,
	}, nil
}
